﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO.Ports;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using Newtonsoft.Json.Linq;
using TSNPro.Communication.Sender;

namespace TSNPro.MyControl
{
    public partial class SerialPortControl : UserControl
    {
        public SerialPortControl()
        {
            InitializeComponent();

            LoadSerialPorts();
        }

        private SerialPortSender _sender;
        public void SetCommunication(SerialPortSender sender)
        {
            _sender = sender;

            cmbPortName.Text = _sender.GetCommParam();
            gbParam.Text = _sender.Name;
            btnOpen.Enabled = !_sender.IsConnected();
        }

        private void LoadSerialPorts()
        {
            // 获取所有串口名
            string[] portNames = SerialPort.GetPortNames();

            // 清空 ComboBox 并添加所有串口
            cmbPortName.Items.Clear();
            foreach (string port in portNames)
            {
                cmbPortName.Items.Add(port);
            }
        }

        private void btnOpen_Click(object sender, EventArgs e)
        {
            JObject obj = new JObject()
            {
                { "Address",cmbPortName.Text }
            };
            _sender.SetConfig(obj);
            if(_sender.Init())
            {
                btnOpen.Enabled = false;
                AppConfig cfg = AppConfig.GetInstance();
                cfg.Write(_sender.Name, "PortName", cmbPortName.Text);
            }
        }

        private void btnClose_Click(object sender, EventArgs e)
        {
            _sender.DisConnectFromHost();
            btnOpen.Enabled = true;
        }
    }
}
